package com.gitee.deeround.javaprotect.agent;

import com.gitee.deeround.javaprotect.agent.util.CommonUtils;
import com.gitee.deeround.javaprotect.agent.util.FileUtils;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @author wanghao 913351190@qq.com
 * @create 2023/11/7 23:21
 */
public class T implements ClassFileTransformer {

    private IE e;

    public T(IE e) {
        this.e = e;
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if (className == null || protectionDomain == null || loader == null) {
            return classfileBuffer;
        }
        try {
            byte[] data = decode(className);
            if (data == null) {
                return classfileBuffer;
            } else {
                return data;
            }
        } catch (Exception e) {
            System.out.println("decode " + className + " error");
            throw new RuntimeException("decode " + className + " error");
        }
    }


    private byte[] decode(String className) {
        String filename = CommonUtils.getClassEncodePath(null, e.en(className.replace("\\", ".").replace("/", ".")));
        if (A.class.getResource(filename) == null) {
            return null;
        }
        byte[] data = FileUtils.toBytes(A.class.getResourceAsStream(filename));
        if (data == null || data.length == 0) {
            return null;
        }
        return e.d(data);
    }
}
